<template>
  <div class="content">
    <div class="TitleBar">
        <TitleBar :imgUrl="url" :Title="'我的购物车'" :info="info"></TitleBar>
    </div>
    <template v-if="cartData.length>=1">
        <div class="table">
            <div class="table_main">
                <el-table ref="multipleTable" :data="cartData" @select="select" @select-all="selectAll" style="width:100%" border>
                    <!-- 商品名称单价数量小计操作 -->
                    <el-table-column type="selection" width="52"></el-table-column>
                    <el-table-column label="" width="110" prop="goods_info.goods_img">
                        <template scope="scope">
                            <img :src="scope.row.goods_info.goods_img" alt="" height="80" width="80">
                        </template>
                    </el-table-column>
                    <el-table-column label="商品名称" width="220" prop="goods_info.goods_name"></el-table-column>
                    <el-table-column label="单价" width="200" prop="goods_info.goods_pprice"></el-table-column>
                    <el-table-column label="数量" width="200" prop="goods_num">
                        <template scope="scope">
                            <el-input-number v-model="scope.row.goods_num" @change="handleChange(scope.row)" :min="1" :max="10" label="描述文字"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计" width="200" prop="goods_info.goods_pprice">
                        <template scope="scope">
                            <div class="pprice">{{ scope.row.goods_info.goods_pprice*scope.row.goods_num}}元</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="block">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="pageNumber"
                :page-sizes="[5,10,15,20,30,50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>
            <div class="table_count flex-between-center">
                <div class="count_left flex-between-center">
                    <div class="count_left_tap" @click="continueShop">继续购物</div>
                    <div style="width:1px;height:16px;background-color:#ccc"></div>
                    <div class="count_left_info">
                        共<span class="left_info_number">{{ total }}</span>件商品,已选择<span class="left_info_number">{{ alreadlySelect }}</span>件
                    </div>
                </div>
                <div class="count_right flex-between-center">
                    <div class="count_right_price flex-between-center">
                        <div class="count_right_text">合计：</div>
                        <div class="count_right_total">{{totalMoney}}元</div>
                    </div>
                    <div class="count_right_tap" @click="toPay">去结算</div>
                </div>
            </div>
        </div>
    </template>
    <template v-else>
        <el-empty :style="{height:screnHeight-206+'px'}" description="您的购物车中还没有商品哦"></el-empty>
    </template>
  </div>
</template>
<script>
import TitleBar from '../components/TitleBar.vue'
import { mapMutations } from 'vuex';
export default {
    data(){
        return{
            url:require('../static/imgs/购物车.png'),
            info:'温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算',
            cartData:[],
            selectArray:[],   //购物车中已经选中的数据对象
            total:null,
            totalMoney:0,
            pageNumber:null,
            pageSize:null,
            screnHeight:document.body.clientHeight,
            selectIds:[], //选中的购物车列表商品id
        }
    },
    components:{
        TitleBar
    },
    computed:{
        // 计算商品已经选中的数量
        alreadlySelect(){
            if(this.selectArray){
                return this.selectArray.length
            }else{
                return 0
            }
        },
    },
    created(){
        this.getData()
    },
    methods:{
        ...mapMutations(['initCartData','initOrderId']),
        // 获取购物车数据
        async getData(pageNumber,pageSize){
            const res = await this.$http.post('/carts/getCarts',{pageNumber,pageSize})
            const selectIds = []
            const selectItem = []
            if(res.status == 200){
                this.cartData = res.data.result.list
                this.total = res.data.result.total
                this.initCartData(res.data.result.list)
                if(this.cartData){
                    this.$nextTick(()=>{
                    this.cartData.forEach((item,index)=>{
                        if(item.selected == true){
                            selectItem.push(item)
                            selectIds.push(item.id)
                            this.selectIds = selectIds
                            this.selectArray = selectItem
                            this.$refs.multipleTable.toggleRowSelection(item)
                            this.totalPrice()
                        }
                    })
                })
                }
            }
        },
        // inputNumber框数量变化触发
        async handleChange(row){
            const {id,selected,goods_num} = row
            this.totalPrice()
            const res = await this.$http.patch('/carts/updateCarts',{id,selected,goods_num})
            if(res.status == 200){
                this.$message({
                    message:res.data.message,
                    type:'success'
                })
            }
        },
        // 单选，单不选功能
        select(selection,row){
            // this.selectArray= selection
            this.totalPrice()
            this.selectIds.push(row.id)
            if(row.selected == false){
                this.$http.post('/carts/multipleOrRadio',{ids:[row.id]}).then((res)=>{
                    if(res.status == 200){
                        row.selected = !row.selected
                        this.getData()
                    }
                })
            }else{
                this.$http.post('/carts/unMultipleOrRadio',{ids:[row.id]}).then((res)=>{
                    if(res.status == 200){
                        row.selected = !row.selected
                        this.getData()
                    }
                })
            }
        },
        // 全选全不选功能
        selectAll(selection){
            if(this.selectIds.length !== this.cartData.length){
                this.$http.post('/carts/selectAll').then(res=>{
                    if(res.status == 200){
                        this.getData()
                        this.$message({
                            message:res.data.message,
                            type:'success'
                        })
                    }
                })
            }else{
                this.$http.post('/carts/unSelectAll').then((res)=>{
                    if(res.status == 200){
                        this.selectIds = []
                        this.totalMoney = 0
                        this.getData()
                        this.$message({
                            message:res.data.message,
                            type:'success'
                        })
                    }
                })
            }
        },
        // 计算商品总价
        totalPrice(){
            let totalMoneyArray = []
            let total = 0
            if(this.selectArray){
                this.selectArray.forEach(item=>{
                    totalMoneyArray.push(item.goods_num*item.goods_info.goods_pprice)
                })
            }
            totalMoneyArray.forEach(item=>{
                total+=item
            })
            this.totalMoney = total
        },
        // 修改按钮
        handleEdit(){
            this.$message({
                message:'编辑功能还没做哦',
                type:'success'
            })
        },
        // 删除按钮
        handleDelete(index,row){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const id = row.id
                const ids = []
                ids.push(id)
                this.deleteCarts(ids)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 删除购物车函数
        async deleteCarts(ids){
            const res = await this.$http.post('/carts/deleteCart',{ids:ids})
            if(res.status == 200){
                this.getData()
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }else{

            }
        },
        handleSizeChange(val){
            this.pageNumber = 1
            this.pageSize = val
            this.getData(this.pageNumber,this.pageSize)
        },
        handleCurrentChange(val){
            this.currentPage = val
            this.pageNumber = val
            this.getData(this.pageNumber,this.pageSize)
        },
        // 继续购物
        continueShop(){
            this.$router.push('/')
        },
        // 去结算
        toPay(){
            // 存储要已选中的--要进行结算的购物车数据id
            this.initOrderId(this.selectArray)
            this.$router.push('/confirmOrder')
            
        }
        
    }
}
</script>

<style scoped>
.flex-between-center{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.table{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
}
.table_main {
    width: 80%;
}
.pprice{
    color: #ff6700;
    font-size: 18px;
}
.table_count{
    width: 80%;
    height: 50px;
    margin-top: 30px;
    background-color: #ffffff;
}
.count_left{
    width: 260px;
    padding-left: 30px;
    color: #a79d9d;
}
.count_left_tap{
    cursor: pointer;
}
.count_left_tap:hover{
    color: #ff6700;
}
.left_info_number{
    color: #ff6700;
    margin-left: 2px;
    margin-right: 2px;
}
.count_right{
    width: 300px;
    color: #ff6700;
}
.count_right_text{
    font-size: 14px;
}
.count_right_total{
    font-size: 20px;
}
.count_right_tap{
    width: 160px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ff6700;
    color: #ffffff;
    cursor: pointer;
}
.count_right_tap:hover{
    background-color:#f25807 ;
}

</style>